//
//  WLLOAuthViewController.swift
//  WLLWeibo
//
//  Created by 王乐乐 on 16/8/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

//typealias  ll = String
class WLLOAuthViewController: UIViewController {
//typedefined
//    var nameee : ll?
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        view = webView
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            return
        }
//    print(url.absoluteString)
//        设置代理
        webView.delegate = self
                // 实例化
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
       /* //请求
        "https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code"
        
        //同意授权后会重定向
        http://www.example.com/response&code=CODE
  */
            setupUI()
    }
     //MARK: - 设置视图
    func setupUI()  {
        view.backgroundColor = RandomColor()
        
        setupNav()
    }
 //MARK: - 设置导航
    func setupNav()  {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoAction")
        
    }
     //MARK: - 监听按钮点击
    /**
     取消
     */
   @objc private func cancleAction()  {
        dismissViewControllerAnimated(true, completion: nil)
    }
    /**
     *  自动填充
     */
   @objc private  func autoAction()  {
        print("自动填充")

    let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPasswd)'"
    //js 注入
    webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    
    }
     //MARK: - 懒加载控件
  private  lazy var webView = UIWebView()
    
}


// MARK: - UIWebViewDelegate
extension WLLOAuthViewController : UIWebViewDelegate{
    /*
     - 监听 webView 将要加载的request
     - 如果不实现 默认 返回true
     - 如果返回 false  停止加载requet
     */
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print(request)
        
        if let urlString = request.URL?.absoluteString  where  urlString.hasPrefix(WBRedirect_uri) {
//            print(urlString)//  http://www.baidu.com/?code=9bbb5c575e217d6939080eea5a9d0aea
            //query 请求参数
            if let query = request.URL?.query {
//                print(query)
                let code = query.substringFromIndex("code=".endIndex)
//                print(code)
            WLLUserAccountViewModel.shareTool.getUserCount(code, finish: { (isSuccess) in
                if !isSuccess{
                    print("请求失败")
                    return
                }
                
                print("请求成功")
                self.dismissViewControllerAnimated(false, completion: { 
                    // 发送通知 切换根控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICATION, object: "oauth")
                })
               
            })
                
            }
            
        }
        
        
        
        return true
    }
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
//        SVProgressHUD.show()
    }
 //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //TODO:目前来说,有 bug, 跳回首页时不消失
//        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
}
//抽取到 ViewModel中去了
 //MARK: - 请求数据
extension WLLOAuthViewController{

    
}














